<?php
#####################################################
# RWCARDS - Joomla E-Cards Componment!
# Copyright (C) 2004/2005 by Ralf Weber
# Company    : LoadBrain
# Homepage   : www.weberr.de
# Version    : 2.1.0
# Date       : 23/11/2005
# License    : Released under GPL
######################################################

defined( '_VALID_MOS' ) or die( 'Direct Access to this location is not allowed.' );


if (!($acl->acl_check( 'administration', 'edit', 'users', $my->usertype, 'components', 'all' )
    | $acl->acl_check( 'administration', 'edit', 'users', $my->usertype, 'components', 'com_rwcards' ))) 
{
  mosRedirect( 'index2.php', _NOT_AUTH );
}

require_once( $mainframe->getPath( 'admin_html' ) );
require_once( $mainframe->getPath( 'class' ) );

$task = trim( mosGetParam( $_REQUEST, 'task', "" ) );
$pid = mosGetParam( $_REQUEST, 'pid', array(0) );
$id = mosGetParam( $_REQUEST, 'id', 0 );
if (!is_array( $pid ))
{
  $pid = array(0);
}

// Standard (D)HTML...
echo ("<div id=\"overDiv\" style=\"position:absolute; visibility:hidden; z-index:1000;\"></div>\n"
 . "\t<script language=\"JavaScript\" src=\"" . $mosConfig_live_site . "/includes/js/overlib_mini.js\"></script>\n");

switch ($task) 
{

  /* Config */
	case "config":
    	RWCardsConfig( $option );
    	break;
		
	case "save_config":
    	RWCardsConfigSave( $option );
    	break;
  
  /* Categoriey */		
	case "categories":
		RWCardsGetCategories($option);
		break;
	
	case "new_category":
		RWCardsNewCategory('0', $option);
		break;

	case "edit_category":
		RWCardsNewCategory( $pid[0], $option ); 
		break;		

	case "save_category":
		RWCardsSaveCategory( $option );
		break;

	case "delete_category":
		RWCardsDeleteCategory(  $pid, $id, $option );
		break;
		
	case "orderup":
		orderCategory( $pid[0], -1, $option );
		break;
	
	case "orderdown":
		orderCategory( $pid[0], 1, $option );
		break;		

	case "publish":
		changeCategory( $pid, 1, $option );
		break;
	
	case "unpublish":
		changeCategory( $pid, 0, $option );
		break;		  
  
  
  /* sentcards */
	case "sentcards":
    	RWCardsManageSentCards( $option );
    	break;

	case "delete_sentcards":
    	RWCardsDeleteSentCards( $pid, $id, $option );
    	break;
		  
  /* about */
	case "about":
    	RWCardsAbout( $option );
    	break;
	case "upload":
    	RWCardsUpload( $option );
    	break;
		
  /* about */
	case "cards":
    	RWCardsListCards( $option );
    	break;

	case "new_card":	
		RWCardsNewCard('0', $option);
		break;

	case "edit_card":
		RWCardsNewCard( $pid[0], $option ); 
		break;		
				
	case "save_card":
		RWCardsSaveCard( $option );
		break;
		
	case "publish_card":
		publishCard( $pid, 1, $option );
		break;
	
	case "unpublish_card":
		publishCard( $pid, 0, $option );
		break;		  

	case "orderup_cards":
		orderCards( $pid[0], -1, $option );
		break;
	
	case "orderdown_cards":
		orderCards( $pid[0], 1, $option );
		break;		

	case "delete_card":
		RWCardsDeleteCard(  $pid, $id, $option );
		break;
		
	default:
		RWCardsMain();
		break;
}


function RWCardsMain()
{
	global $database, $mainframe;
		
	$database->setQuery("SELECT count(*) FROM #__rwcards_category");
	$category = $database->loadResult();

	$imgFiles = mosReadDirectory( $mainframe->getCfg( 'absolute_path' ) . "/images/stories/cards" );
	
	rwcards_html::setRWCardsMainscreen();
	rwcards_html::setRWCardsMenu(_ADMIN_RWCARDS_MENU_TITLE . " " . _RWCARDS_VERSION, $category, $imgFiles);
}


// CONFIG
function RWCardsConfig($option)
{
	global $database;
	include_once($GLOBALS['mosConfig_absolute_path'].'/administrator/components/com_rwcards/admin.rwcards.config.html.php');
	
	$database->setQuery("SELECT * FROM #__rwcardsconfig");
	$rows = $database->loadObjectList();
	
	rwcards_html::setRWCardsMainscreen();
	rwcards_config_html::setRWCardsConfig($option, _ADMIN_RWCARDS_MENU_TITLE . " " . _RWCARDS_VERSION, $rows[0]);
	rwcards_html::setRWCardsFooter();
}

function RWCardsConfigSave($option)
{
	global $database;
	
	$database->setQuery("update #__rwcardsconfig set lifetime = '" .  $_REQUEST['rwcards_config_lifetime'] . "', maxadvanced  = '" .  $_REQUEST['rwcards_config_maxadvanced'] . "', cardsperpage  = '" .  $_REQUEST['rwcards_config_cardsperpage'] . "' , attachement  = '" .  $_REQUEST['rwcards_config_attachement'] . "', rowssperpage  = '" .  $_REQUEST['rwcards_config_rowssperpage'] . "', backgroundcolor  = '" .  $_REQUEST['rwcards_config_backgroundcolor'] . "', captcha  = '" .  $_REQUEST['rwcards_config_captcha'] . "'");

	if (!$database->query())
	{
		echo "<script> alert('".$database->getErrorMsg()."'); </script>";
	}
	mosRedirect( "index2.php?option=$option" );
}


// ABOUT
function RWCardsAbout($option)
{
	global $database;
	include_once($GLOBALS['mosConfig_absolute_path'].'/administrator/components/com_rwcards/admin.rwcards.about.html.php');
	
	rwcards_html::setRWCardsMainscreen();
	rwcards_about_html::setRWCardsAbout($option, _ADMIN_RWCARDS_MENU_TITLE . " " . _RWCARDS_VERSION);
	rwcards_html::setRWCardsFooter();
}


// UPLOAD
function RWCardsUpload( $option )
{
	include_once($GLOBALS['mosConfig_absolute_path'].'/administrator/components/com_rwcards/admin.rwcards.upload.html.php');

	rwcards_html::setRWCardsMainscreen();
	rwcards_upload_html::setRWCardsUpload(_ADMIN_RWCARDS_MENU_TITLE . " " . _RWCARDS_VERSION);
	rwcards_html::setRWCardsFooter();
	echo "<script language='JavaScript'>window.open('index2.php?option=com_media', 'MediaManager','left=10,top=10,width=800,height=600,scrollbars=1');</script>";
}

// CATEGORIES
function RWCardsGetCategories($option)
{
	global $mainframe, $database;

  	include_once($GLOBALS['mosConfig_absolute_path'].'/administrator/components/com_rwcards/admin.rwcards.categories.html.php');
  
	$limit = $mainframe->getUserStateFromRequest( "viewlistlimit", 'limit', 10 );
	$limitstart = $mainframe->getUserStateFromRequest( "view{$option}limitstart", 'limitstart', 0 );
	$search = $mainframe->getUserStateFromRequest( "search{$option}", 'search', '' );
	$search = $database->getEscaped( trim( strtolower( $search ) ) );
	$where = $search ? " WHERE category_kategorien_name LIKE '%" . $search . "%'" : "";
	//var_dump($search); exit;
	// get the total number of records
	$database->setQuery( "SELECT COUNT(*) FROM #__rwcards_category $where" );
	$total = $database->loadResult();
	
	require_once( "includes/pageNavigation.php" );
	$pageNav = new mosPageNav( $total, $limitstart, $limit  );
	
	$q_raw = "SELECT p.*, u.name AS editor"
	  . "\nFROM #__rwcards_category AS p"
	  . "\nLEFT JOIN #__users AS u ON u.id = p.checked_out"
	  . "\n" . $where
	  . "\nORDER BY ordering, category_kategorien_name ASC"
	  . "\nLIMIT $pageNav->limitstart, $pageNav->limit";
	$database->setQuery( $q_raw );
	$rows = $database->loadObjectList();
	
	echo '<p class="error">' . $database->getErrorMsg() . '</p>';
	
	rwcards_html::setRWCardsMainscreen();
	rwcards_categories_html::RWCardsListCategories( $rows, $pageNav, $search, $option );
	rwcards_html::setRWCardsFooter();
}

function RWCardsNewCategory( $id, $option ) 
{
	global $database, $my, $mosConfig_absolute_path;
	include_once($GLOBALS['mosConfig_absolute_path'].'/administrator/components/com_rwcards/admin.rwcards.categories.html.php');
	
	$row = new rwcards_category( $database );
	// load the row from the db table
	$row->load( $id );
	
	// fail if checked out not by 'me'
	if ($row->checked_out && $row->checked_out <> $my->id) 
	{
		mosRedirect( "index2.php?option=$option",'The module $row->category_kategorien_name is currently being edited by another administrator.' );
	}
	
	if ($id) 
	{
	// do stuff for existing records
		$row->checkout( $my->id );
	} 
	else 
	{
	// do stuff for new records
		$row->ordering = 999;
	}
	
	if ($id) 
	{
		// build the html select list for ordering
		$order = mosGetOrderingList( "SELECT ordering AS value, category_kategorien_name AS text"
		. "\nFROM #__rwcards_category"
		. "\nWHERE published >= 0 ORDER BY ordering"
		);
		$olist = mosHTML::selectList( $order, 'ordering', 'class="inputbox" size="1"',
		'value', 'text', intval( $row->ordering ) );
	} 
	else 
	{
		$olist = "<input type=\"hidden\" name=\"ordering\" value=\"$row->ordering\" />" . _ADMIN_NEW_ITEMS_LAST;
	}
	
	rwcards_html::setRWCardsMainscreen();
	rwcards_categories_html::RWCardsEditCategory( $row, $option, $olist );
	rwcards_html::setRWCardsFooter();  
  
}

function RWCardsSaveCategory( $option ) 
{
	global $database, $my;
	
	$row = new rwcards_category( $database );
	//var_dump($row); exit;
	if (!$row->bind( $_POST )) 
	{
		echo "<script> alert('".$row->getError()."'); window.history.go(-1); </script>\n";
		exit();
	}
	
	// pre-save checks
	if (!$row->check()) 
	{
		echo "<script> alert('".$row->getError()."'); window.history.go(-1); </script>\n";
		exit();
	}
	// save the changes
	if (!$row->store())
	{
		echo "<script> alert('".$row->getError()."'); window.history.go(-1); </script>\n";
		exit();
	}
	
	$row->checkin();
	$row->updateOrder();
	
	mosRedirect( "index2.php?option=$option&task=categories" );
}

function RWCardsDeleteCategory( $pid, $id, $option )
{
	global $database;

	if (!is_array( $pid ) || count( $pid ) < 1) 
	{
		echo "<script> alert('Select an item to delete'); window.history.go(-1);</script>\n";
		exit;
	}
	
	if (count( $pid )) 
	{
		$pids = implode( ',', $pid );
		$database->setQuery( "DELETE FROM #__rwcards_category WHERE id IN ($pids)" );
		if (!$database->query()) 
		{
	 		echo "<script> alert('".$database->getErrorMsg()."'); window.history.go(-1); </script>\n";
		}
	}

  mosRedirect( "index2.php?option=$option&task=categories&pid[]=".$id );
}

function orderCategory( $pid, $inc, $option ) {
  global $database;
  echo $pid . " " . $inc . " " . $option;
  $row = new rwcards_category( $database );
  var_dump($row); //exit;
  $row->load( $pid );
  $row->move( $inc, "published >= 0" );

  mosRedirect( "index2.php?option=$option&task=categories" );
}


/**
* Change the state publish / unpublish of a Category
*/
function changeCategory(  $pid=null, $state=0, $option ) 
{
  global $database, $my;

  if (count( $pid ) < 1) 
  {
    $action = $publish == 1 ? 'publish' : 'unpublish';
    echo "<script> alert('Select a record to $action'); window.history.go(-1);</script>\n";
    exit;
  }

  $pids = implode( ',', $pid );

  $database->setQuery( "UPDATE #__rwcards_category SET published='$state'"
  . "\nWHERE id IN ($pids) AND (checked_out=0 OR (checked_out='$my->id'))"
  );
  if (!$database->query()) {
    echo "<script> alert('".$database->getErrorMsg()."'); window.history.go(-1); </script>\n";
    exit();
  }

  if (count( $pid ) == 1) {
    $row = new rwcards_category( $database );
    $row->checkin( intval( $pid[0] ) );
  }

  mosRedirect( "index2.php?option=$option&task=categories" );
}

/* sentcards */
function RWCardsManageSentCards( $option )
{
	global $mainframe, $database;

  	include_once($GLOBALS['mosConfig_absolute_path'].'/administrator/components/com_rwcards/admin.rwcards.sentcards.html.php');
  
  	/** First delete all entries that are too old... **/
  	$database->setQuery( "select lifetime FROM #__rwcardsconfig" );
	$rowsConfig = $database->loadObjectList();
	$lifetimeDate = date("Y-m-d", mktime(0, 0, 0, date("m")  , date("d")-$rowsConfig[0]->lifetime, date("Y")));
	
	$database->setQuery( "select writtenOn FROM #__rwcardsdata" );
	$rows = $database->loadObjectList();

	for ($i=0; $i<count($rows); $i++) 
	{
		if ($rows[$i]->writtenOn <= $lifetimeDate)
		{
			//echo "DELETE FROM #__rwcardsdata WHERE writtenOn <= '" . $lifetimeDate . "'<br>";
			$database->query( $database->setQuery("DELETE FROM #__rwcardsdata WHERE writtenOn <= '" . $lifetimeDate . "'" ) );
		}
	}

	$limit = $mainframe->getUserStateFromRequest( "viewlistlimit", 'limit', 10 );
	$limitstart = $mainframe->getUserStateFromRequest( "view{$option}limitstart", 'limitstart', 0 );
	$search = $mainframe->getUserStateFromRequest( "search{$option}", 'search', '' );
	$search = $database->getEscaped( trim( strtolower( $search ) ) );
	$where = $search ? " WHERE nameTo LIKE '%" . $search . "%' or nameFrom LIKE '%" . $search . "%' or emailTo LIKE '%" . $search . "%' or emailFrom LIKE '%" . $search . "%'" : "";
	
	// get the total number of records
	$database->setQuery( "SELECT COUNT(*) FROM #__rwcardsdata $where" );
	$total = $database->loadResult();
	
	require_once( "includes/pageNavigation.php" );
	$pageNav = new mosPageNav( $total, $limitstart, $limit  );
	
	$q_raw = "SELECT p.*"
	  . "\nFROM #__rwcardsdata AS p"
	  . "\n" . $where
	  . "\nORDER BY writtenOn , id ASC"
	  . "\nLIMIT $pageNav->limitstart, $pageNav->limit";
	$database->setQuery( $q_raw );
	$rows = $database->loadObjectList();
	
	echo '<p class="error">' . $database->getErrorMsg() . '</p>';
	rwcards_html::setRWCardsMainscreen();
	rwcards_sentcards_html::RWCardsListSentCards( $rows, $pageNav, $search, $option, $rowsConfig[0]->lifetime );
	rwcards_html::setRWCardsFooter();

}

function RWCardsDeleteSentCards( $pid, $id, $option )
{
	global $database;

	if (!is_array( $pid ) || count( $pid ) < 1) 
	{
		echo "<script> alert('Select an item to delete'); window.history.go(-1);</script>\n";
		exit;
	}
	
	if (count( $pid )) 
	{
		$pids = implode( ',', $pid );
		$database->setQuery( "DELETE FROM #__rwcardsdata WHERE id IN ($pids)" );
		if (!$database->query()) 
		{
	 		echo "<script> alert('".$database->getErrorMsg()."'); window.history.go(-1); </script>\n";
		}
	}

  mosRedirect( "index2.php?option=$option&task=sentcards&pid[]=".$id );
}

/** Cards */
function RWCardsListCards( $option )
{
	global $mainframe, $database;
	$categories = array();
	
	include_once($GLOBALS['mosConfig_absolute_path'].'/administrator/components/com_rwcards/admin.rwcards.cards.html.php');
  
	// categories
	$sql = "SELECT * FROM #__rwcards_category order by ordering";
	$database->setQuery($sql);
	$res = $database->loadObjectList();

	$limit = $mainframe->getUserStateFromRequest( "viewlistlimit", 'limit', 10 );
	$limitstart = $mainframe->getUserStateFromRequest( "view{$option}limitstart", 'limitstart', 0 );
	$search = $mainframe->getUserStateFromRequest( "search{$option}", 'search', '' );
	$search = $database->getEscaped( trim( strtolower( $search ) ) );
	$where = $search ? " and autor LIKE '%" . $search . "%' or p.email LIKE '%" . $search . "%' or description LIKE '%" . $search . "%'" : "";

	// is a category choosed
	if ( isset($_REQUEST["kategorien_id"]) )
	{
	// get the total number of records
	$database->setQuery( "SELECT count(*) FROM #__rwcards, #__rwcards_category where #__rwcards.category_id = '" . $_REQUEST["kategorien_id"] . "' and #__rwcards_category.id = '" . $_REQUEST["kategorien_id"] . "'" );

	$total = $database->loadResult();

	require_once( "includes/pageNavigation.php" );
	$pageNav = new mosPageNav( $total, $limitstart, $limit  );
    foreach ($res as $key => $val)
		{
			if ($val->id == $_REQUEST["kategorien_id"])
			{
        $selectedCategory = $val->category_kategorien_name;
				$selectedCategoryId = $val->id;
			}
			$categories[] = mosHTML::makeOption($val->id, $val->category_kategorien_name);
		}
		$categoryList = mosHTML::selectList( $categories, 'kategorien_id', "class=\"inputbox\" size=\"1\", onchange=\"changeCategory();\"", 'value', 'text', $selectedCategoryId);
		$category = $database->loadObjectList();
		
   	$database->setQuery("SELECT p.*, u.name AS editor FROM (#__rwcards AS p, #__rwcards_category) LEFT JOIN #__users AS u ON (u.id = p.checked_out) where p.category_id = '" . $_REQUEST["kategorien_id"] . "' and #__rwcards_category.id = '" . $_REQUEST["kategorien_id"] . "' " . $where . "  ORDER BY ordering, id, autor ASC LIMIT $pageNav->limitstart, $pageNav->limit");
  }
  else
  {

	// get the total number of records
	$database->setQuery( "SELECT count(*) FROM #__rwcards, #__rwcards_category where #__rwcards.category_id  = '" . $res[0]->id . "' and #__rwcards_category.id = '" . $res[0]->id . "'" . $where);

	$total = $database->loadResult();
	
	require_once( "includes/pageNavigation.php" );
	$pageNav = new mosPageNav( $total, $limitstart, $limit  );
	
		foreach ($res as $key => $val)
		{
			$categories[] = mosHTML::makeOption($val->id, $val->category_kategorien_name);
		}
		$categoryList = mosHTML::selectList( $categories, 'kategorien_id', "class=\"inputbox\" size=\"1\", onchange=\"changeCategory();\"", 'value', 'text');
		$category = $database->loadObjectList();
		$selectedCategory = @$category[0]->category_kategorien_name;
	  $database->setQuery("SELECT p.*, u.name AS editor FROM (#__rwcards AS p, #__rwcards_category) LEFT JOIN #__users AS u ON (u.id = p.checked_out) where p.category_id  = '" . $res[0]->id . "' and #__rwcards_category.id = '" . $res[0]->id . "' " . $where . "  ORDER BY ordering, id, autor ASC LIMIT $pageNav->limitstart, $pageNav->limit");
  }
	$rows = $database->loadObjectList();
	
	echo '<p class="error">' . $database->getErrorMsg() . '</p>';
	
	rwcards_html::setRWCardsMainscreen();
	rwcards_cards_html::RWCardsListCards( $rows, $pageNav, $search, $option, $selectedCategory, $categoryList );
	rwcards_html::setRWCardsFooter();
}

/**
* Change the state publish / unpublish of a Card
*/
function publishCard(  $pid=null, $state=0, $option ) 
{
  global $database, $my;

  if (count( $pid ) < 1) 
  {
    $action = $publish == 1 ? 'publish' : 'unpublish';
    echo "<script> alert('Select a record to $action'); window.history.go(-1);</script>\n";
    exit;
  }

  $pids = implode( ',', $pid );

  $database->setQuery( "UPDATE #__rwcards SET published='$state'"
  . "\nWHERE id IN ($pids) AND (checked_out=0 OR (checked_out='$my->id'))"
  );
  if (!$database->query()) {
    echo "<script> alert('".$database->getErrorMsg()."'); window.history.go(-1); </script>\n";
    exit();
  }

  if (count( $pid ) == 1) {
    $row = new rwcards_cards( $database );
    $row->checkin( intval( $pid[0] ) );
  }

  mosRedirect( "index2.php?option=$option&task=cards" );
}

function orderCards( $pid, $inc, $option ) 
{
  global $database;

  $row = new rwcards_cards( $database );
  $row->load( $pid );
  $row->move( $inc, "published >= 0" );

  mosRedirect( "index2.php?option=$option&task=cards" );
}

function RWCardsNewCard( $id, $option ) 
{
	global $database, $my, $mosConfig_absolute_path, $mainframe;
	include_once($GLOBALS['mosConfig_absolute_path'].'/administrator/components/com_rwcards/admin.rwcards.cards.html.php');
	$categories = array();
	$selectedPicture = "";
	$selected = "";
	
	$imgFiles = mosReadDirectory( $mainframe->getCfg( 'absolute_path' ) . "/images/stories/cards" );
	$images = array();

	foreach ($imgFiles as $file)
	{
		if ( preg_match("@_t@", $file) )
		{
			continue;
		}
		if (eregi( "jpg|png|gif", $file ))
		{
			$images[] = mosHTML::makeOption( $file );
		}
	}
	// We only need the 'value' to lookup the selected options.
	if ($id)
	{
		$database->setQuery( "SELECT picture FROM #__rwcards where #__rwcards.id = '" . $id . "'" );
		$selectedPicture = $database->loadResult();
	}
	
	$imageFiles = mosHTML::selectList( $images, 'picture', "class=\"inputbox\" size=\"1\" onchange=\"changeImagePreview();\"", 'value', 'text', $selectedPicture);

	// categories ..where published > 0 ...
	$sql = "SELECT * FROM #__rwcards_category order by category_kategorien_name";
	$database->setQuery($sql);
	$res = $database->loadObjectList();
	
	foreach ($res as $key => $val)
	{
		$categories[] = mosHTML::makeOption($val->id, $val->category_kategorien_name);
	}
	
	// We only need the 'value' to lookup the selected options.
	if($id)
	{	
		$database->setQuery( "SELECT #__rwcards_category.id as catId FROM #__rwcards_category, #__rwcards where #__rwcards.category_id =  #__rwcards_category.id and #__rwcards.id = '" . $id . "'" );
		$selected = $database->loadResult();
	}
	$categoryList = mosHTML::selectList( $categories, 'category_id', "class=\"inputbox\" size=\"1\"" , 'value', 'text',  $selected);

	$row = new rwcards_cards( $database );
	// load the row from the db table
	$row->load( $id );
	
	// fail if checked out not by 'me'
	if ($row->checked_out && $row->checked_out <> $my->id) 
	{
		mosRedirect( "index2.php?option=$option",'The enrty $row->autor is currently being edited by another administrator.' );
	}
	
	if ($id) 
	{
	// do stuff for existing records
		$row->checkout( $my->id );
	} 
	else 
	{
	// do stuff for new records
		$row->ordering = 999;
	}
	
	if ($id) 
	{
		// build the html select list for ordering
		$order = mosGetOrderingList( "SELECT ordering AS value, autor AS text"
		. "\nFROM #__rwcards"
		. "\nWHERE published >= 0 ORDER BY ordering"
		);
		$olist = mosHTML::selectList( $order, 'ordering', 'class="inputbox" size="1"',
		'value', 'text', intval( $row->ordering ) );
	} 
	else 
	{
		$olist = "<input type=\"hidden\" name=\"ordering\" value=\"$row->ordering\" />" . _ADMIN_NEW_ITEMS_LAST;
	}
	
	rwcards_html::setRWCardsMainscreen();
	rwcards_cards_html::RWCardsEditCard( $row, $option, $imageFiles, $categoryList, $olist );
	rwcards_html::setRWCardsFooter();  
  
}

function RWCardsSaveCard( $option ) 
{
	global $database, $my;
	
	/** create a thumbnail */
	RWCardsCreateThumbnails($_POST['picture']);
	
	$row = new rwcards_cards( $database );
	if (!$row->bind( $_POST )) 
	{
		echo "<script> alert('".$row->getError()."'); window.history.go(-1); </script>\n";
		exit();
	}
	
	// pre-save checks
	if (!$row->check()) 
	{
		echo "<script> alert('".$row->getError()."'); window.history.go(-1); </script>\n";
		exit();
	}
	// save the changes
	if (!$row->store())
	{
		echo "<script> alert('".$row->getError()."'); window.history.go(-1); </script>\n";
		exit();
	}
	
	$row->checkin();
	$row->updateOrder();
	
	mosRedirect( "index2.php?option=$option&task=cards" );
}


function RWCardsCreateThumbnails($bild)
{
       global $mainframe;
       $breite = 120;
       $hoehe = 80;  
	   
       $name = strtolower( substr($bild, 0, -4) ) . "_t.jpg"; 

	   $size = GetImageSize ($mainframe->getCfg( 'absolute_path' ) . "/images/stories/cards/" . $bild); 

       // zugross & quer
       if ($size[0] > $breite && $size[1] > $hoehe  && $size[0] >= $size[1]) 
       {
              $sizemin[0] = $breite;
              $sizemin[1] = $hoehe;
       }
       // zugross & hochkant
       else if ($size[0] > $breite && $size[1] > $hoehe && $size[1] > $size[0]) 
       {
              $sizemin[0] = $hoehe;
              $sizemin[1] = $breite;
       }
       // breite zu gross:
       else if ($size[0] > $breite )
       {
              $sizemin[0] = $breite;
              $sizemin[1] = $size[1];
       }
       // hoehe zu gross:
       else if ($size[1] > $hoehe )
       {
              $sizemin[0] = $size[0];
              $sizemin[1] = $hoehe;
       }
       // bild ok:
       else 
       {
              $sizemin[0] = $sizemin[0];
              $sizemin[1] = $sizemin[1];
       }
       
	   if (eregi( "\.gif", $bild ))
	   {
	   	   $im = ImageCreateFromGif($mainframe->getCfg('absolute_path') . "/images/stories/cards/" . $bild);
	   }
	   else
	   {
       	$im = @imagecreatefromjpeg($mainframe->getCfg('absolute_path') . "/images/stories/cards/" . $bild); 
       }
	   $small = imagecreatetruecolor($sizemin[0], $sizemin[1] );
	   #var_dump($small);
       ImageCopyResampled($small, $im, 0, 0, 0, 0, $sizemin[0], $sizemin[1], $size[0], $size[1]);
       ImageDestroy($im);
       
	   if (eregi( "\.gif", $bild ))
	   {
		imagegif($small, $mainframe->getCfg( 'absolute_path' ) . "/images/stories/cards/" . $name, "100%");
	   }
	   else
	   {
       if (!ImageJPEG($small, $mainframe->getCfg( 'absolute_path' ) . "/images/stories/cards/" . $name, "100%"))
       {
              echo "<font color=red><b>";
              echo _RWCARD_THUMBNAIL_ERROR;
              echo "</b></font><br>\n";
       }
	   }
}

function RWCardsDeleteCard( $pid, $id, $option )
{
	global $database;

	if (!is_array( $pid ) || count( $pid ) < 1) 
	{
		echo "<script> alert('Select an item to delete'); window.history.go(-1);</script>\n";
		exit;
	}
	
	if (count( $pid )) 
	{
		$pids = implode( ',', $pid );
		$database->setQuery( "DELETE FROM #__rwcards WHERE id IN ($pids)" );
		//echo "DELETE FROM #__rwcards WHERE id IN ($pids)"; exit;
		if (!$database->query()) 
		{
	 		echo "<script> alert('".$database->getErrorMsg()."'); window.history.go(-1); </script>\n";
		}
	}

  mosRedirect( "index2.php?option=$option&task=cards&pid[]=".$id );
}

?>
